package cn.zzdt4j.config.toolkit;

/**
 * The type Simple read write lock.
 *
 * @author by <a href="mailto:ligang941012@gmail.com">gang.Li</a>
 * @since 2023 /11/8 15:19
 */
public class SimpleReadWriteLock {

    private static final int FREE_STATUS = -1;
    private volatile int status = 0;

    public synchronized boolean tryReadLock() {
        if (isWriteLocked()) {
            return false;
        } else {
            status++;
            return true;
        }

    }

    public synchronized void releaseReadLock() {
        status--;
    }

    public synchronized boolean tryWriteLock() {
        if (!isFree()) {
            return false;
        } else {
            status = FREE_STATUS;
            return true;
        }
    }

    public synchronized void releaseWriteLock() {
        status = 0;
    }

    private boolean isFree() {
        return status == 0;
    }

    private boolean isWriteLocked() {
        return status < 0;
    }
}
